package com.ashlikun.verifycodeview;

import android.content.ClipboardManager;
import android.content.Context;
import android.util.AttributeSet;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputConnectionWrapper;

/**
 * 作者　　: 李坤
 * 创建时间: 2024/5/27　14:31
 * 邮箱　　：496546144@qq.com
 * <p>
 * 功能介绍：处理粘贴的EditText
 */
public class PasteEditText extends androidx.appcompat.widget.AppCompatEditText {
    protected OnPasteCallback onPasteCallback;

    public PasteEditText(Context context) {
        super(context);
    }

    public PasteEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public PasteEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setOnPasteCallback(OnPasteCallback onPasteCallback) {
        this.onPasteCallback = onPasteCallback;
    }

    protected String paste() {
        ClipboardManager cmb = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
        try {
            return cmb.getPrimaryClip().getItemAt(0).getText().toString();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 输入法上面的粘贴
     */
    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        return new PromotionInputConnection(super.onCreateInputConnection(outAttrs), true);
    }

    /**
     * 系统的粘贴
     */
    @Override
    public boolean onTextContextMenuItem(int id) {
        if (id == android.R.id.paste) {
            if (onPasteCallback != null) {
                postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        onPasteCallback.onPaste(paste());
                    }
                }, 20);
            }
        }
        return super.onTextContextMenuItem(id);
    }

    protected class PromotionInputConnection extends InputConnectionWrapper {
        public PromotionInputConnection(InputConnection target, boolean mutable) {
            super(target, mutable);
        }

        @Override
        public boolean commitText(CharSequence text, int newCursorPosition) {
            if (onPasteCallback != null && text != null && text.length() > 1) {
                onPasteCallback.onPaste(text.toString());
                return true;
            } else {
                return super.commitText(text, newCursorPosition);
            }
        }
    }

    interface OnPasteCallback {
        void onPaste(String text);
    }
}
